﻿using Greg.XmlEditor.Business;
using Greg.XmlEditor.Presentation.Presenters;

namespace Greg.XmlEditor.Presentation.Commands.Concrete
{
	public class ApplyStyleCommand : CommandBase
	{
		private readonly MasterPresenter presenter;
		private readonly ITransformationService transformationService;
		private readonly IInteractionManager interaction;

		public ApplyStyleCommand(MasterPresenter presenter, ITransformationService transformationService, IInteractionManager interaction)
		{
			this.presenter = presenter;
			this.transformationService = transformationService;
			this.interaction = interaction;
		}

		/// <summary>
		/// Refreshes the command state.
		/// </summary>
		public override void Refresh()
		{
			this.IsEnabled = this.presenter.CurrentDocument != null &&
			                 this.presenter.CurrentDocument is DocumentPresenter &&
			                 ((DocumentPresenter) this.presenter.CurrentDocument).Style.IsPersistent;
		}

		/// <summary>
		/// Executes the command logics.
		/// </summary>
		public override void Invoke()
		{
			var document = (DocumentPresenter)this.presenter.CurrentDocument;

			var result = this.transformationService.Transform(document.Text, document.Style.FullPath);

			if (result.Succeeded)
			{
				this.interaction.ShowTrasformedDocument(result.Message);
			}
			else
			{
				this.interaction.ShowError(result.Message);
			}
		}
	}
}
